<template>
  <a-modal
    v-model:visible="visible"
    modal-class="metric-compare-modal"
    title-align="start"
    @close="closeModal"
    @before-open="beforeOpen"
    width="455px"
  >
    <template #title>
      <span class="title-text">指标对比配置</span>
    </template>
    <a-form
      ref="compareFormRef"
      :model="model"
      @submit.prevent
      auto-label-width
    >
      <a-form-item
        field="compareName"
        label="对比项名称"
        :rules="[{ required: true, message: '请输入对比项名称' }]"
        :validate-trigger="['change', 'input']"
        show-colon
      >
        <a-input
          v-model="model.compareName"
          :limit="20"
          show-word-limit
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item
        label="对比时间点"
        :field="
          model.dateCondition.dateMode === 'FIXDATE'
            ? 'dateCondition.fixDate'
            : 'dateCondition.offset'
        "
        :rules="[{ required: true, message: '请选择对比时间点' }]"
        :validate-trigger="['change']"
        class="compare-time-form-item"
        show-colon
      >
        <a-select
          v-model="model.dateCondition.dateMode"
          :options="[
            { label: '相对日期', value: 'BEFORE' },
            { label: '固定日期', value: 'FIXDATE' }
          ]"
          @change="
            compareFormRef.resetFields([
              'dateCondition.offset',
              'dateCondition.fixDate'
            ])
          "
        >
          <template #arrow-icon>
            <IconCaretDown size="12" />
          </template>
        </a-select>
        <component
          :is="getCurrentTimeComponent(currentTimeframe!)"
          v-if="model.dateCondition.dateMode === 'FIXDATE'"
          v-model="model.dateCondition.fixDate"
        ></component>
        <template v-else>
          <a-input-number
            v-model="model.dateCondition.offset"
            :min="1"
            :precision="0"
          />
          <span style="white-space: nowrap">{{ currentTimeLabel + '前' }}</span>
        </template>
      </a-form-item>
      <a-form-item
        label="对比值"
        field="compareType"
        :rules="[{ required: true, message: '请选择对比值' }]"
        :validate-trigger="['change']"
        show-colon
      >
        <a-select
          v-model="model.compareType"
          :options="[
            { label: '差值', value: 'GAPVAL' },
            { label: '差值百分比', value: 'GAPPERCENT' },
            { label: '对比值数值', value: 'VAL' }
          ]"
        >
          <template #arrow-icon>
            <IconCaretDown size="12" />
          </template>
        </a-select>
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="visible = false"> 取消 </a-button>
      <a-button @click="handleOk" type="primary"> 确定 </a-button>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
import { ref, watch, computed, inject, Ref, watchEffect } from 'vue';
import { statisticalPeriodUnitOption } from '../../type';
import { getCurrentTimeComponent } from '../../hooks';
import { IconCaretDown } from '@arco-design/web-vue/es/icon';
import { cloneDeep } from 'lodash';

const props = withDefaults(
  defineProps<{
    modelValue: boolean;
    data: any;
  }>(),
  {
    modelValue: false,
    data: null
  }
);
const emits = defineEmits(['update:modelValue', 'ok']);
const currentTimeframe = inject<Ref>('current-timeframe');
const currentTimeLabel = computed(() => {
  return (
    (
      statisticalPeriodUnitOption.find(
        (item) => item.value === currentTimeframe!.value
      ) || {}
    ).label || '日'
  );
});

const visible = ref(false);
const compareFormRef = ref();

const model = ref({
  compareName: '',
  compareType: '',
  dateCondition: {
    dateMode: '',
    offset: undefined,
    fixDate: '',
    timeUnit: currentTimeframe!.value
  }
});

watchEffect(() => {
  model.value.dateCondition.timeUnit = currentTimeframe!.value;
});

// watch(
//   () => props.data,
//   (val) => {
//     if (val) {
//       model.value = cloneDeep(props.data);
//     } else {
//       compareFormRef.value && compareFormRef.value.resetFields();
//     }
//   },
//   { deep: true }
// );

const handleOk = () => {
  compareFormRef.value.validate((err: any) => {
    if (!err) {
      emits('ok', cloneDeep(model.value));
      visible.value = false;
    }
  });
};
// 关闭弹窗
const closeModal = () => {
  if (!props.data) {
    compareFormRef.value.clearValidate();
  }
  emits('update:modelValue', false);
};

// 打开弹窗，重新赋值（点击确定有效）
const beforeOpen = () => {
  if (props.data) {
    model.value = cloneDeep(props.data);
  } else {
    compareFormRef.value && compareFormRef.value.resetFields();
    model.value.dateCondition.dateMode = '';
  }
};
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
  }
);
</script>
<style lang="scss">
.metric-compare-modal {
  .title-text {
    color: var(--color-text-1);
    font-weight: 600;
    font-size: 16px;
  }

  .compare-time-form-item .arco-form-item-content {
    & > .arco-select,
    & > .arco-input-number {
      flex: 1;
      margin-right: 10px;
    }
    & > .arco-select:last-child {
      margin-right: 0;
    }
  }
}
</style>
